import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:xvideos/hj_utils/date_time_util.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/light_model.dart';

import '../../config/config.dart';
import '../../hj_model/user/mobile_login_model.dart';
import '../../hj_model/user/user_info_model.dart';
import '../../hj_model/user/wallet_model_entity.dart';
import '../../hj_utils/text_util.dart';
import '../../hj_utils/utils.dart';
import '../net/net_manager.dart';

/// 建立一个AppStore
/// 目前它的功能只有切换主题

final globalStore = GlobalStore();

class GlobalStore extends ChangeNotifier {
  static final GlobalStore _instance = GlobalStore._();
  GlobalStore._();
  factory GlobalStore() => _instance;

  ///密码相关
  final password = <int>[];
  bool isChecked = false;
  UserInfoModel? meInfo; //个人信息
  WalletModelEntity? wallet; //钱包信息

  /// 初始化密码
  init() async {
    final nativePass = await lightKV.getString(Config.PASS_WORD_KEY);
    if (nativePass != null) {
      try {
        final temp = json.decode(nativePass);
        password.addAll(List<int>.from(temp));
      } catch (e) {
        print('e');
      }
    }
  }

  Future<bool?> setLockPassword(List<int> ps) async {
    final res = await lightKV.setString(Config.PASS_WORD_KEY, json.encode(ps));
    if (res == true) {
      showToast('设置密码成功');
      password.addAll(ps);
      notifyListeners();
      return true;
    }

    return res;
  }

  Future<bool?> closeLockPassword(List<int> ps) async {
    if (ps.join('') != password.join('')) {
      showToast('密码验证失败，请重新输入～');
      return false;
    }
    final res = await lightKV.setString(Config.PASS_WORD_KEY, json.encode([]));
    if (res == true) {
      showToast('取消锁屏密码成功');
      password.clear();
      notifyListeners();
    }

    return res;
  }

  Future<bool?> checkLockPassword(List<int> ps) async {
    if (ps.join('') != password.join('')) {
      showToast('密码验证失败，请重新输入～');
      return false;
    }
    isChecked = true;
    return true;
  }

  bool isMe(int? uid) {
    if (uid == null) return false;
    return (meInfo?.uid ?? 0) == uid;
  }

  ///是否充值vip（不包括推广）
  bool isRechargeVIP() {
    return (meInfo?.isVip ?? false) && (meInfo?.vipLevel ?? 0) > 0;
  }

  int getInvitedays() {
    if (meInfo == null) return 0;
    final createD = meInfo?.createdAt ?? '';
    if (createD.isEmpty) return 0;
    final cd = DateTime.parse(createD).toLocal();
    final now = DateTime.now().toLocal();
    final diff = now.difference(cd);
    return diff.inDays;
  }

  ///vip（包括推广）
  bool isVIP() {
    return (meInfo?.isVip ?? false);
  }

  // 0 普通用户
// 1 普通会员
// 2 超级会员
// 3 暗网会员
// 4 换妻会员
  bool isAWVIP() {
    return (meInfo?.vipLevel ?? 0) >= 3;
  }

  //acg vip,观看动漫
  bool isACGVIP() {
    return (meInfo?.vipLevel ?? 0) > 0;
  }

  bool isVIPTwoLevel() {
    return (meInfo?.vipLevel ?? 0) == 2;
  }

  UserInfoModel? getMe() {
    return meInfo;
  }

  WalletModelEntity? getWallet() {
    return wallet;
  }

  // 会员提示
  String vipTime({bool? hasVipName = true}) {
    int level = meInfo?.vipLevel ?? 0;
    final vipName = meInfo?.vipName ?? '';
    final addName = hasVipName ?? false;
    if (level > 0) {
      return '${(addName && vipName.isNotEmpty) ? '$vipName ' : ''}会员到期时间 ${DateTimeUtil.utcTurnYear(meInfo?.vipExpireDate, char: '-')}';
    } else {
      return '开通会员免费看大片 剩余可下载次数${wallet?.downloadCount ?? 0}';
    }
  }

  /// 刷新钱包信息
  Future<WalletModelEntity?> refreshWallet({bool refresh = true}) async {
    final remoteWallet = await MineService.fetchWalletData();
    if (refresh) notifyListeners();
    wallet = remoteWallet;
    return remoteWallet;
  }

  /// 二维码登陆
  /// [refresh] 是否刷新关联globalstate的状态的页面 ==false就只是一个网络请求了
  Future<UserInfoModel?> loginByQr(String qr, {String paste = "", bool refresh = true}) async {
    String devType = await getDevType();
    UserInfoModel? userInfo;
    String buildID = await netManager.getFixedPkgName();
    netManager.setToken('');

    userInfo = await MineService.devLogin("", qr, devType, Platform.operatingSystem, Config.innerVersion, buildID, "", paste);

    if (TextUtil.isNotEmpty(userInfo?.token)) {
      netManager.setToken(userInfo!.token!);
    }
    if (userInfo?.loginType != 1) {}
    if (refresh) {
      meInfo = userInfo;
      notifyListeners();
    }
    return userInfo;
  }

  /// 设备登陆
  /// [refresh] 刷新所有user全局状态
  Future<UserInfoModel?> loginByDevice(String deviceId, {String paste = "", bool refresh = true}) async {
    String devType = await getDevType();
    UserInfoModel? userInfo;
    String buildID = await netManager.getFixedPkgName();
    var deviceIdSign = Config.getDevToken(deviceId);

    userInfo = await MineService.devLogin(
      deviceId,
      "",
      devType,
      Platform.operatingSystem,
      Config.innerVersion,
      buildID,
      deviceIdSign,
      paste,
    );

    if (TextUtil.isNotEmpty(userInfo?.token)) {
      await netManager.setToken(userInfo?.token);
    }
    if (userInfo?.loginType != 1) {}
    if (refresh) {
      meInfo = userInfo;
      notifyListeners();
    }
    return userInfo;
  }

  /// 手机号码登陆
  /// [refresh] 刷新所有user全局状态
  Future<UserInfoModel?> mobileLogin(String mobile, String code, {String paste = "", bool refresh = true}) async {
    String devType = await getDevType();
    String buildID = await netManager.getFixedPkgName();
    String deviceID = await getDeviceOaid();
    MobileLoginModel? mobileModel;
    MobileLoginModel? resp =
        await MineService.mobileLogin(mobile, code, deviceID, devType, Platform.operatingSystem, Config.innerVersion, buildID, paste);
    if (resp != null) {
      mobileModel = resp;
      showToast('登录成功');
    } else {
      showToast('登录失败');
    }
    if (TextUtil.isNotEmpty(mobileModel?.userInfo?.token)) {
      netManager.setToken(mobileModel?.userInfo?.token);
    }
    if (mobileModel?.userInfo != null) {
      var userInfo = mobileModel?.userInfo;
      if (userInfo?.loginType != 1) {}
      if (refresh) {
        meInfo = userInfo;
        notifyListeners();
      }
    }
    return mobileModel?.userInfo;
  }

  /// 组合业务，更新用户信息并获取用户新的信息
  /// 如果map为空就是单纯的获取用户信息
  /// [refresh] 刷新所有user全局状态 刷新会调用consumer 包含的widget
  Future<UserInfoModel?> updateUserInfo({Map<String, dynamic>? map, bool refresh = true}) async {
    UserInfoModel? userInfo;
    bool res = false;

    /// 是更新用户信息 这里要区分下
    if ((map?.keys.length ?? 0) > 0) {
      res = await MineService.updateUserInfo(map);
      if (res) {
        userInfo = await MineService.getUserInfo();
        if (refresh && userInfo != null) {
          meInfo = userInfo;
          notifyListeners();
        }
        return userInfo;
      }
      return null;
    }
    userInfo = await MineService.getUserInfo();
    if (refresh && userInfo != null) {
      meInfo = userInfo;
      notifyListeners();
    }
    return meInfo;
  }
}
